<template>
	<view class="basic">
		<view class="form form-a">
			<view class="form-group">
				<view 
					class="form-item" 
					v-for="(item, index) in baseData" :key='index'
					:class="{'form-item-ver': item.type == 'images'}">
					<view class="form-item-header"><text v-if="!item.isHideLabel">{{item.label}}：</text></view>
					<view class="form-item-body" v-if="item.type == 'select'">
						<picker :value="item.index" :range="item.options"
							:range-key="item.field == 'district' ? 'name' : 'dict_label' "
							@change="bindPickerChange($event, item.field)">
							<view class="select">
								<view class="select-selected">
									{{ item.value | getDictLabel(item.options, item.field == 'district' ? 'district' : 'dict_value', item.field == 'district' ? 'name' : 'dict_label') || '请选择' }}
								</view>
								<view class="select-btn">
									<uni-icons class="icon" type="arrowdown" font-family="iconfont" size="15"
										color="#a9a9a9">
									</uni-icons>
								</view>
							</view>
						</picker>
					</view>

					<view class="form-item-body" v-else-if="item.type == 'addr'">
						<view class="addr">
							<input class="form-control addr-input" v-model="item.value" type="text" placeholder="请输入" />
							<view class="addr-btn" @tap="getPos">
								<image class="icon" mode="aspectFit" src="@/static/icon/icon_location.png">
								</image>
							</view>
						</view>
					</view>

					<view class="form-item-body" v-else-if="item.type == 'inputGroup'">
						<view class="area" v-for="(option, ind) in item.options" :key="ind">
							<view class="area-btn" @tap="changeArea(ind, item.field)">
								<uni-icons :type="ind == 0 ? 'plus-filled' : 'minus-filled'"  size="18" :color="ind == 0 ? '#fe8f00' : '#c40808'"></uni-icons>
							</view>
							<block v-for="(opt, i) in option" :key="i">
								<view class="area-item">
									<input class="form-control" v-model="opt.value" type="text"
										:placeholder="opt.label" @input="inputCount(item.field, item.targetField)"/>
								</view>
								<view class="area-sign" v-if="i < option.length -1">*</view>
							</block>
						</view>
					</view>
					<view class="form-item-body" v-else-if="item.type == 'images'">
						<view class="list list-photo">
							<view class="list-group">
								<view class="list-item" v-for="(option, index) in item.options" :key="index">
									<view class="card card-a" @tap="bindPreviewImage(item.field, index)">
										<view class="card-header">
										</view>
										<view class="delete" @tap.stop.prevent="bindDelPic(item.field,index)">
											<image class="icon" mode="aspectFit" src="@/static/icon/delete-icon.png">
											</image>
										</view>
										<view class="card-body">
											<image class="pic" mode="aspectFit" :src="option">
											</image>
										</view>
									</view>
								</view>
								<view class="list-item" v-show="item.options.length < 4">
									<view class="card card-a card-add" @tap="bindChooseImage(item.field)">
										<view class="card-body">
											<uni-icons class="icon" type="plusempty" font-family="iconfont" size="42"
												color="#a9a9a9">
											</uni-icons>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="form-item-body" v-else>
						<input class="form-control" :disabled="item.disabled" type="text" v-model="item.value" placeholder="请输入" />
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	import {queryNearbyMedia,getMediaDetailByMap,getDicts,uploadPic, getMediaType} from '@/api/configure.js';
	import {deepClone,getToken,toLogin,getLocation,moveToLocation,mergeUrls,cleanData,chooseImage,previewImage} from '@/util/util.js';
	import configUrl from '@/util/url.js';

	export default {
		props: {
			value:{
				type:  Object,
				default: () => {
					return {}
				}
			}
		},
		data() {
			return {
				baseData: [{
					type: 'addr',
					field: 'describeAddress',
					label: '地址',
					value: ''
				}, {
					type: 'input',
					field: 'buildingPointName',
					label: '点位名称',
					value: ''
				}, {
					type: 'input',
					field: 'road',
					label: '路段',
					value: ''
				}, {
					type: 'select',
					field: 'adType',
					label: '广告类别',
					value: '',
					index: null,
					options: []
				}, {
					type: 'select',
					field: 'mediaTypeLv1',
					label: '媒体类别',
					value: '',
					index: null,
					options: [],
					targetField: 'mediaTypeLv2'
				}, {
					isHideLabel: true,
					type: 'select',
					field: 'mediaTypeLv2',
					label: '媒体类别',
					value: '',
					index: null,
					options: [],
					targetField: 'mediaTypeLv3'
				},{
					isHideLabel: true,
					type: 'select',
					field: 'mediaTypeLv3',
					label: '媒体类别',
					value: '',
					index: null,
					options: []
				},{
					type: 'select',
					field: 'mediaStatus',
					label: '媒体状态',
					value: '',
					index: null,
					options: []
				}, {
					type: 'inputGroup',
					field: 'size',
					label: '尺寸m*m',
					value: '',
					index: null,
					targetField: 'mediaNumber',
					options: [[{
						field: 'length',
						value: '',
						label: '长'
					}, {
						field: 'width',
						value: '',
						label: '宽'
					}, {
						field: 'mediaCount',
						value: '',
						label: '数量'
					}]]
				}, {
					type: 'input',
					field: 'area',
					label: '总面积m²',
					value: ''
				}, {
					type: 'select',
					field: 'facilityType',
					label: '设施类型',
					value: '',
					index: null,
					options: []
				}, {
					type: 'select',
					field: 'orientation',
					label: '朝向',
					value: '',
					index: null,
					options: []
				}, {
					type: 'input',
					field: 'mediaNumber',
					label: '媒体面数',
					value: '',
					disabled: true
				}, {
					type: 'select',
					field: 'district',
					label: '行政区域',
					value: '',
					index: null,
					options: []
				}, {
					type: 'images',
					field: 'advertiseUrl',
					label: '现状照片',
					value: '',
					index: null,
					options: [],
					urls: [],
				}],
				longitude: '',
				latitude: '',
				portAddress: ''
			}
		},
		methods: {
			receivePos(data) {
				this.longitude = data.longitude;
				this.latitude = data.latitude;

				let address = data.address;
				
				this.portAddress = address;
				
				let target = this.baseData.find(item => item.field == 'describeAddress');

				target.value = address;
			},
			getPos() {
				let data = {};
				
				if(this.longitude) {
					data = {longitude: this.longitude , latitude: this.latitude };
				}
				
				let url = '/pages/map/index';
				
				url = mergeUrls(url, data);
				
				uni.navigateTo({
					url: url
				});
			},
			async getAllDicts() {
				let ds = [
					getDicts({'type': 'selectAdType'}),       //广告类别
					getDicts({'type': 'selectSetType'}),      //设置形式
					getDicts({'type': 'selectFacilityType'}), //设施类型
					getDicts({'type': 'selectMediaStatus'}),  //媒体状态
					getDicts({'type': 'selectIsLegal'}),      //是否合法
					getDicts({'type': 'orientation'}),        //朝向
					getDicts({'type': 'selectDivision'}),      //行政区域
					getMediaType({level: 1, parentid: null})
				];

				let dits = await Promise.all(ds);

				this.baseData.forEach(item => {
					if (item.field == 'adType') {
						item.options = dits[0].data.slice(0);
					} else if (item.field == 'setType') {
						item.options = dits[1].data.slice(0);
					} else if (item.field == 'facilityType') {
						item.options = dits[2].data.slice(0);
					} else if (item.field == 'mediaStatus') {
						item.options = dits[3].data.slice(0);
					} else if (item.field == 'orientation') {
						item.options = dits[5].data.slice(0);
					} else if (item.field == 'district') {
						item.options = dits[6].data.slice(0);
					} else if (item.field == 'mediaTypeLv1') {
						let options= dits[7].data.slice(0);
						
						item.options = options.map( option => ({dict_label: option.name, dict_value: option.id}));
					} else {
						
					}
				})
			},
			async getMediaType(obj) {
				let params = {
					parentid: obj.value
				}
				
				if(obj.targetField == 'mediaTypeLv2'){
					params.level = 2;
				} else {
					params.level = 3;
				}
				
				let {code, data} = await getMediaType(params);
				
				let targetField = this.baseData.find(item => item.field == obj.targetField);
				
				targetField.options = data.map( option => ({dict_label: option.name, dict_value: option.id}));
				
			},
			async clearPicker(targetField){
				let target = this.baseData.find(select => select.field == targetField);
				
				
				target.value = null;
				target.index = null;
				
				target.options = [];
				
				if(target.targetField){
					this.clearPicker(target.targetField);
				}
			},
			bindPickerChange(e, field) {
				let index = e.detail.value;
				let select = this.baseData.find(item => item.field == field);

				select.index = index;

				if (select.field == 'district') {
					select.value = select.options[index]['district'];
				} else {
					select.value = select.options[index]['dict_value'];
				}
				
				if(select.targetField){
					this.clearPicker(select.targetField);
				}
				
				if(select.field == 'mediaTypeLv1' || select.field == 'mediaTypeLv2'){
					this.getMediaType(select);
				}
			},
			async bindChooseImage(field) {
				let {
					tempFilePaths
				} = await chooseImage();

				let data = {
					tempFilePath: tempFilePaths[0],
					name: 'avatarfile'
				}

				let imgUrl = await uploadPic(data);

				if (imgUrl) {
					let images = this.baseData.find(item => item.field == field);
					images.urls.push(imgUrl);

					let url = `${configUrl.CASEIMAGE_URL}${imgUrl}`;

					images.options.push(url);
				}
			},
			async bindDelPic(field, index) {
				let pic = this.baseData.find(item => item.field == field);

				pic.options.splice(index, 1);
				pic.urls.splice(index, 1);
			},
			bindPreviewImage(field, index) {
				let pic = this.baseData.find(item => item.field == field);

				let data = {
					current: index,
					urls: pic.options
				}

				previewImage(data);
			},
			checkRequired(){
				let isPass = true;
				
				let notPass = this.baseData.find( item => {
					let isChecked = false;
					
					if(item.type == 'images'){
						isChecked = true;
					} else if(item.type == 'inputGroup'){
						isChecked = true;
					}else {
						if(item.value) {
							isChecked = true;
						} 
					}
					
					return !isChecked;
				})
				
				if(notPass) {
					uni.showToast({
						title: `${notPass.label}不能为空`,
						duration: 2000,
						icon: 'none'
					});
					
					isPass = false;
				}
				
				return isPass;
			},
			sendParams() {
				let data = {};
				
				let isPass = this.checkRequired();
				
				if (!isPass) {
					return data;
				}
				
				this.baseData.forEach(item => {
					if (item.field == 'size') {
						
						let mediaCount = [];
						let width = [];
						let length = [];
						
						item.options.forEach(option => {
							option.forEach(opt => {
								if(opt.field == 'mediaCount'){
									mediaCount.push(opt.value);
								} else if (opt.field == 'width') {
									width.push(opt.value);
								} else {
									length.push(opt.value);
								}
							})
						})
						
						data['mediaCount'] = mediaCount.join(',');
						data['width'] = width.join(',');
						data['length'] = length.join(',');
					} else if (item.type == 'images') {
						data[item.field] = item.urls.join(',');
					} else {
						data[item.field] = item.value;
					}
				});

				data.lng = this.longitude;
				data.lat = this.latitude;
				
				data.portAddress = this.portAddress;
				
				return data;
			},
			setVal() {
				this.baseData.forEach( item => {
					if (item.field == 'size') {
						let val = JSON.parse(this.value[item.field]);
						
						if(val.length == 0) {
							return 
						}
						
						item.options = [];
						
						item.options = val.map((v) => {
							return [{
								field: 'length', 
								value: v.length,
								label: '长',
							}, {
								field: 'width',
								value: v.width,
								label: '宽',
							}, {
								field: 'mediaCount',
								value: v.media_count,
								label: '数量',
							}]
						})
						
					} else if (item.field == 'advertiseUrl') {
						if (this.value['url']) {
							let urls = [];
							
							if( this.value['url'].indexOf(',') == -1) {
								urls = [this.value['url']];
							} else {
								urls = this.value['url'].split(',');
							}
							
							item.options = urls.map(url => `${configUrl.CASEIMAGE_URL}${url}`);
							
							item.urls = urls;
						}
					} else {
						item.value =  this.value[item.field] || '';
						
						if((item.field == 'mediaTypeLv1' && item.value) || (item.field == 'mediaTypeLv2' && item.value)){
							
							this.getMediaType(item);
						}
					}
				})
				
				this.longitude = this.value.lng;
				this.latitude = this.value.lat;
				this.portAddress = this.value.portAddress;
			},
			changeArea(index, field) {
				let area = this.baseData.find( item => item.field === 'size');
				
				let a = [{
					field: 'length',
					value: '',
					label: '长'
				}, {
					field: 'width',
					value: '',
					label: '宽'
				}, {
					field: 'mediaCount',
					value: '',
					label: '数量'
				}]
				
				if ( index == 0 ) {
					let canAdd = true;
					
					canAdd = area.options.every(option => option.every(opt => opt.value))
					
					if (canAdd) {
						area.options.push(a);
					} else {
						uni.showToast({
							title: '请核对尺寸信息',
							duration: 2000,
							icon: 'none'
						});
					}
				} else {
					area.options.splice(index,1);
					this.inputCount(field, area.targetField);
					
				}
			},
			inputArea(field) {
				let size = this.baseData.find( item => item.field === field);
				
				let count = size.options.reduce((total, item) => {
					return total + item[0]['value'] * item[1]['value'] * item[2]['value']
				}, 0);
				
				let area = this.baseData.find( item => item.field === 'area');
				
				area.value = count;
			},
			
			inputCount(field, targetField) {
				let area = this.baseData.find( item => item.field === field);
				
				let target = this.baseData.find( item => item.field === targetField);
				let count = 0;
				
				area.options.forEach(option => {
					let value = option[2]['value'];
					
					if (/^(0|[1-9]\d*)$\b/gm.test(value)) {
						count = count + Number(value);
					} else {
						
					}
				})
				
				target.value = count;
				
				this.inputArea(field);
			},
			async init() {
				await this.getAllDicts();
			
			}
		},
		created() {
			uni.$on('code/index/getPos', this.receivePos);
			this.init();
		},
		mounted() {},
		watch: {
			value: {
				handler(val, oldVal) {
					this.setVal();
				},
				deep: true
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form {
		.form-group {
			.form-item {
				margin-bottom: 23rpx;
				padding: 0rpx 80rpx;
				display: flex;

				.form-item-header {
					height: 46rpx;
					padding: 6rpx 0rpx;
					font-size: 28rpx;
					line-height: 34rpx;
					text-align: justify;
					box-sizing: border-box;
				}

				.form-item-body {
					.cals {
						.cals-group {
							display: flex;
							justify-content: space-between;

							.cals-item {
								border: 1rpx solid #d7d7d7;
								border-radius: 4rpx;
								background-color: #ffffff;
								position: relative;
								top: 0rpx;
								left: 0rpx;
								flex-grow: 1;

								.cals-item-left {
									padding: 4rpx 6rpx;
									padding-right: 46rpx;
									font-size: 24rpx;
									line-height: 30rpx;
									height: 46rpx;
									box-sizing: border-box;
								}

								.cals-item-right {
									width: 46rpx;
									height: 46rpx;
									position: absolute;
									top: 0rpx;
									right: 0rpx;
									display: flex;
									justify-content: center;
									align-items: center;

									.icon {
										width: 24rpx;
										height: 24rpx;
									}
								}
							}

							.cals-sign {
								margin: 23rpx 9rpx;
								width: 30rpx;
								height: 1rpx;
								background-color: #c6c6c8;
							}
						}

					}

					.form-control {
						padding: 6rpx 6rpx;
						border: 1rpx solid #d7d7d7;
						border-radius: 4rpx;
						font-size: 24rpx;
						line-height: 30rpx;
						background-color: #ffffff;
					}

					.select {
						border: 1rpx solid #d7d7d7;
						border-radius: 4rpx;
						background-color: #ffffff;
						position: relative;
						top: 0rpx;
						left: 0rpx;

						.select-selected {
							padding: 8rpx 6rpx;
							padding-right: 46rpx;
							font-size: 24rpx;
							line-height: 30rpx;
							height: 46rpx;
							box-sizing: border-box;
						}

						.select-btn {
							width: 46rpx;
							height: 46rpx;
							position: absolute;
							top: 0rpx;
							right: 0rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}

					.addr {
						position: relative;
						top: 0rpx;
						left: 0rpx;

						.addr-input {
							padding-right: 46rpx;
						}

						.addr-btn {
							width: 46rpx;
							height: 46rpx;
							position: absolute;
							top: 0rpx;
							right: 0rpx;
							display: flex;
							justify-content: center;
							align-items: center;

							.icon {
								width: 61.8%;
								height: 61.8%;
							}
						}
					}

					.area {
						display: flex;
						position: relative;
						top: 0rpx;
						left: 0rpx;
						margin-bottom: 10rpx;
						.area-item {}
						.area-sign {
							padding: 10rpx 8rpx 8rpx 8rpx;
							font-size: 24rpx;
							line-height: 30rpx;
							height: 46rpx;
							box-sizing: border-box;
						}
						.area-btn{
							width: 50rpx;
							height: 50rpx;
							position: absolute;
							top: 0rpx;
							right: -50rpx;
							display: flex;
							justify-content: center;
							align-items: center;
						}
					}
				}

				&.form-item-ver {
					flex-direction: column;

					.form-item-body {
						width: 100%;
					}
				}
			}
		}
	}

	.form-a {
		.form-item-header {
			width: 160rpx;

			&:after {
				content: "";
				display: inline-block;
				width: 100%;
			}
		}

		.form-item-body {
			width: calc(100% - 160rpx);
		}
	}

	.list {
		&.list-photo {
			.list-group {
				display: flex;
				flex-wrap: wrap;
				.list-item {
					margin-bottom: 20rpx;
					width: 25%;
					display: flex;
					justify-content: center;
				}
			}
		}
	}

	.card {
		&.card-a {
			width: 123rpx;
			height: 116rpx;
			position: relative;
			top: 0rpx;
			left: 0rpx;

			.card-header {
				width: 100%;
				height: 31rpx;
				position: absolute;
				top: 0rpx;
				left: 0rpx;
				background-color: #000000;
				opacity: 0.3;
				z-index: 2;
			}

			.delete {
				width: 31rpx;
				height: 31rpx;
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				z-index: 3;
				display: flex;
				justify-content: center;
				align-items: center;

				.icon {
					width: 20rpx;
					height: 20rpx;
				}
			}

			.card-body {
				height: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #ffffff;
				border: 1rpx solid #d9d9d9;

				.pic {
					width: 100%;
					height: 100%;
				}
			}
		}
	}
</style>
